import {
    UPLOAD_API,
    TUTOR_API,
    COURSE_API
} from '@/API.js';

/**
 ******************************
 ******** 请求相关的函数 ********
 *****************************
 */
export async function uploadFiles(images) {
    /*
     * images: 一个图片的本地路径列表
     * ret: 返回一个promise，表示上传多个文件
     */
    const urlFlag = 'res.jsktesting.com';
    let imageUrl = [];
    for (let image of images) {
        //如果已经是url，那么跳过上传
        if(image.indexOf(urlFlag) != -1) {
            imageUrl.push(image);
            continue;
        }
        //否则上传
        try {
            let [error, res] = await uni.uploadFile({
                url: UPLOAD_API.url,
                filePath: image,
                name: 'file',
                header: {
                    'http-token': getApp().globalData.user.token
                }
            });
            if(error) {
                toast(error);
            }
            imageUrl.push(JSON.parse(res.data).path);
        } catch (e) {
            toast(e);
        }
    }
    return imageUrl;
}

export async function requestCreateQu(sendMessage) {
    try {
        let [err, res] = await uni.request({
            url: TUTOR_API.createQu.url,
            method: TUTOR_API.createQu.method,
            header: {
                'http-token': getApp().globalData.user.token
            },
            data: sendMessage,
        });
        if(err) {
            toast(err);
        }
        return res;
    } catch (e) {
        console.log(e);
        toast(e);
    }
}

export async function requestDiscussion(question_id) {
    try{
        let[err, res] = await uni.request({
            url: TUTOR_API.discussions.url,
            method: TUTOR_API.discussions.method,
            header: {
                'http-token': getApp().globalData.user.token
            },
            data: {
                question_id: question_id
            }
        });
        if(err) {
            toast(err);
        }
        return res;
    }catch(e) {
        console.log(e);
        toast(e);
    }
}

export async function requestCourseName(course_id) {
    try{
        let[err, res] = await uni.request({
            url: COURSE_API.course.url,
            method: COURSE_API.course.method,
            header: {
                'http-token': getApp().globalData.user.token
            },
            data: {
                course_id,
            }
        });
        if(err) {
            toast(err);
        }
        return res.data.title;
    }catch(e) {
        console.log(e);
        toast(e);
    }
}


/**
 ******************************
 ********* 一些辅助函数 *********
 *****************************
 */

export function toast(title) {
    uni.showToast({
        icon: 'none',
        title
    });
}
